import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/front/HomePage.vue')
    },
    {
      path: '/category/:type',
      name: 'category',
      component: () => import('../views/front/CategoryPage.vue'),
      props: true
    },
    {
      path: '/news/:id',
      name: 'newsDetail',
      component: () => import('../views/front/NewsDetailPage.vue'),
      props: true
    },
    {
      path: '/search',
      name: 'search',
      component: () => import('../views/front/SearchResultPage.vue')
    },
    // 管理后台路由
    {
      path: '/admin/login',
      name: 'adminLogin',
      component: () => import('../views/admin/LoginPage.vue')
    },
    {
      path: '/admin',
      name: 'adminLayout',
      component: () => import('../views/admin/AdminLayout.vue'),
      redirect: '/admin/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('../views/admin/DashboardPage.vue')
        },
        {
          path: 'news',
          name: 'newsManagement',
          component: () => import('../views/admin/NewsManagementPage.vue')
        },
        {
          path: 'news/create',
          name: 'createNews',
          component: () => import('../views/admin/NewsEditorPage.vue')
        },
        {
          path: 'news/edit/:id',
          name: 'editNews',
          component: () => import('../views/admin/NewsEditorPage.vue'),
          props: true
        }
      ]
    },
    // 404页面
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('../views/NotFoundPage.vue')
    }
  ],
  scrollBehavior() {
    // 页面切换时滚动到顶部
    return { top: 0 }
  }
})

// 路由守卫 - 检查管理员登录状态
router.beforeEach((to, from, next) => {
  // 获取token
  const token = localStorage.getItem('token')
  
  // 如果访问管理页面（除了登录页）且没有token，重定向到登录页
  if (to.path.startsWith('/admin') && to.path !== '/admin/login' && !token) {
    next('/admin/login')
  } else {
    next()
  }
})

export default router